import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../config/theme/theme_manager.dart';

/// 通用输入框组件
/// 提供统一的输入框样式和功能
class CommonInput extends StatefulWidget {
  /// 控制器
  final TextEditingController? controller;

  /// 标签文本
  final String? label;

  /// 提示文本
  final String? hintText;

  /// 帮助文本
  final String? helperText;

  /// 错误文本
  final String? errorText;

  /// 前缀图标
  final IconData? prefixIcon;

  /// 后缀图标
  final IconData? suffixIcon;

  /// 后缀图标点击回调
  final VoidCallback? onSuffixIconTap;

  /// 输入类型
  final TextInputType keyboardType;

  /// 输入格式限制
  final List<TextInputFormatter>? inputFormatters;

  /// 是否密码输入
  final bool isPassword;

  /// 是否只读
  final bool readOnly;

  /// 是否启用
  final bool enabled;

  /// 最大行数
  final int? maxLines;

  /// 最小行数
  final int? minLines;

  /// 最大长度
  final int? maxLength;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  /// 提交回调
  final ValueChanged<String>? onSubmitted;

  /// 焦点变化回调
  final ValueChanged<bool>? onFocusChanged;

  /// 点击回调
  final VoidCallback? onTap;

  /// 验证器
  final String? Function(String?)? validator;

  /// 输入框样式
  final InputStyle inputStyle;

  /// 输入框大小
  final InputSize inputSize;

  /// 自定义边框半径
  final double? borderRadius;

  /// 自定义背景颜色
  final Color? backgroundColor;

  /// 自定义边框颜色
  final Color? borderColor;

  /// 自定义焦点边框颜色
  final Color? focusedBorderColor;

  /// 自定义文本样式
  final TextStyle? textStyle;

  /// 内边距
  final EdgeInsetsGeometry? contentPadding;

  /// 是否显示字符计数
  final bool showCounter;

  /// 是否自动焦点
  final bool autofocus;

  /// 文本对齐方式
  final TextAlign textAlign;

  /// 文本输入动作
  final TextInputAction? textInputAction;

  const CommonInput({
    super.key,
    this.controller,
    this.label,
    this.hintText,
    this.helperText,
    this.errorText,
    this.prefixIcon,
    this.suffixIcon,
    this.onSuffixIconTap,
    this.keyboardType = TextInputType.text,
    this.inputFormatters,
    this.isPassword = false,
    this.readOnly = false,
    this.enabled = true,
    this.maxLines = 1,
    this.minLines,
    this.maxLength,
    this.onChanged,
    this.onSubmitted,
    this.onFocusChanged,
    this.onTap,
    this.validator,
    this.inputStyle = InputStyle.outline,
    this.inputSize = InputSize.medium,
    this.borderRadius,
    this.backgroundColor,
    this.borderColor,
    this.focusedBorderColor,
    this.textStyle,
    this.contentPadding,
    this.showCounter = false,
    this.autofocus = false,
    this.textAlign = TextAlign.start,
    this.textInputAction,
  });

  @override
  State<CommonInput> createState() => _CommonInputState();
}

class _CommonInputState extends State<CommonInput> {
  late FocusNode _focusNode;
  bool _isFocused = false;
  bool _isPasswordVisible = false;
  String? _errorText;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _focusNode.addListener(_onFocusChanged);
    _errorText = widget.errorText;
  }

  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChanged);
    _focusNode.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(CommonInput oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.errorText != oldWidget.errorText) {
      setState(() {
        _errorText = widget.errorText;
      });
    }
  }

  void _onFocusChanged() {
    setState(() {
      _isFocused = _focusNode.hasFocus;
    });
    widget.onFocusChanged?.call(_isFocused);
  }

  void _onChanged(String value) {
    // 实时验证
    if (widget.validator != null) {
      final error = widget.validator!(value);
      if (error != _errorText) {
        setState(() {
          _errorText = error;
        });
      }
    }
    widget.onChanged?.call(value);
  }

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (widget.label != null) ...[
          Text(
            widget.label!,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: themeManager.contrastColor,
            ),
          ),
          const SizedBox(height: 8),
        ],
        TextFormField(
          controller: widget.controller,
          focusNode: _focusNode,
          keyboardType: widget.keyboardType,
          inputFormatters: widget.inputFormatters,
          obscureText: widget.isPassword && !_isPasswordVisible,
          readOnly: widget.readOnly,
          enabled: widget.enabled,
          maxLines: widget.maxLines,
          minLines: widget.minLines,
          maxLength: widget.maxLength,
          onChanged: _onChanged,
          onFieldSubmitted: widget.onSubmitted,
          onTap: widget.onTap,
          autofocus: widget.autofocus,
          textAlign: widget.textAlign,
          textInputAction: widget.textInputAction,
          style: widget.textStyle ?? _getTextStyle(themeManager),
          decoration: _getInputDecoration(themeManager),
        ),
        if (widget.helperText != null && _errorText == null) ...[
          const SizedBox(height: 4),
          Text(
            widget.helperText!,
            style: TextStyle(
              fontSize: 12,
              color: themeManager.contrastColor.withOpacity(0.6),
            ),
          ),
        ],
        if (_errorText != null) ...[
          const SizedBox(height: 4),
          Text(
            _errorText!,
            style: const TextStyle(
              fontSize: 12,
              color: Colors.red,
            ),
          ),
        ],
        if (widget.showCounter && widget.maxLength != null) ...[
          const SizedBox(height: 4),
          Align(
            alignment: Alignment.centerRight,
            child: Text(
              '${widget.controller?.text.length ?? 0}/${widget.maxLength}',
              style: TextStyle(
                fontSize: 12,
                color: themeManager.contrastColor.withOpacity(0.6),
              ),
            ),
          ),
        ],
      ],
    );
  }

  /// 获取输入框装饰
  InputDecoration _getInputDecoration(ThemeManager themeManager) {
    final borderRadius =
        BorderRadius.circular(widget.borderRadius ?? _getBorderRadius());
    final contentPadding = widget.contentPadding ?? _getContentPadding();

    // 计算颜色
    final backgroundColor =
        widget.backgroundColor ?? _getBackgroundColor(themeManager);
    final borderColor = widget.borderColor ?? _getBorderColor(themeManager);
    final focusedBorderColor =
        widget.focusedBorderColor ?? themeManager.primaryColor;
    const errorBorderColor = Colors.red;

    // 根据样式创建边框
    InputBorder border;
    InputBorder focusedBorder;
    InputBorder errorBorder;

    switch (widget.inputStyle) {
      case InputStyle.outline:
        border = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(color: borderColor, width: 1),
        );
        focusedBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(color: focusedBorderColor, width: 2),
        );
        errorBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: const BorderSide(color: errorBorderColor, width: 1),
        );
        break;
      case InputStyle.underline:
        border = UnderlineInputBorder(
          borderSide: BorderSide(color: borderColor, width: 1),
        );
        focusedBorder = UnderlineInputBorder(
          borderSide: BorderSide(color: focusedBorderColor, width: 2),
        );
        errorBorder = const UnderlineInputBorder(
          borderSide: BorderSide(color: errorBorderColor, width: 1),
        );
        break;
      case InputStyle.filled:
        border = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide.none,
        );
        focusedBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(color: focusedBorderColor, width: 2),
        );
        errorBorder = OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: const BorderSide(color: errorBorderColor, width: 1),
        );
        break;
    }

    return InputDecoration(
      hintText: widget.hintText,
      hintStyle: TextStyle(
        color: themeManager.contrastColor.withOpacity(0.5),
        fontSize: _getFontSize(),
      ),
      prefixIcon: widget.prefixIcon != null
          ? Icon(
              widget.prefixIcon,
              color: _isFocused ? focusedBorderColor : borderColor,
              size: _getIconSize(),
            )
          : null,
      suffixIcon:
          _buildSuffixIcon(themeManager, focusedBorderColor, borderColor),
      filled: widget.inputStyle == InputStyle.filled,
      fillColor: backgroundColor,
      contentPadding: contentPadding,
      border: border,
      enabledBorder: border,
      focusedBorder: focusedBorder,
      errorBorder: errorBorder,
      focusedErrorBorder: errorBorder,
      counterText: widget.showCounter ? null : '',
    );
  }

  /// 构建后缀图标
  Widget? _buildSuffixIcon(
      ThemeManager themeManager, Color focusedColor, Color normalColor) {
    if (widget.isPassword) {
      return IconButton(
        icon: Icon(
          _isPasswordVisible ? Icons.visibility_off : Icons.visibility,
          color: _isFocused ? focusedColor : normalColor,
          size: _getIconSize(),
        ),
        onPressed: () {
          setState(() {
            _isPasswordVisible = !_isPasswordVisible;
          });
        },
      );
    }

    if (widget.suffixIcon != null) {
      return IconButton(
        icon: Icon(
          widget.suffixIcon,
          color: _isFocused ? focusedColor : normalColor,
          size: _getIconSize(),
        ),
        onPressed: widget.onSuffixIconTap,
      );
    }

    return null;
  }

  /// 获取文本样式
  TextStyle _getTextStyle(ThemeManager themeManager) {
    return TextStyle(
      fontSize: _getFontSize(),
      color: widget.enabled
          ? themeManager.contrastColor
          : themeManager.contrastColor.withOpacity(0.5),
    );
  }

  /// 获取背景颜色
  Color _getBackgroundColor(ThemeManager themeManager) {
    if (widget.inputStyle == InputStyle.filled) {
      return themeManager.isDarkMode ? Colors.grey[800]! : Colors.grey[100]!;
    }
    return Colors.transparent;
  }

  /// 获取边框颜色
  Color _getBorderColor(ThemeManager themeManager) {
    if (_errorText != null) {
      return Colors.red;
    }
    return themeManager.dividerColor;
  }

  /// 获取边框半径
  double _getBorderRadius() {
    switch (widget.inputSize) {
      case InputSize.small:
        return 6;
      case InputSize.medium:
        return 8;
      case InputSize.large:
        return 10;
    }
  }

  /// 获取内边距
  EdgeInsetsGeometry _getContentPadding() {
    switch (widget.inputSize) {
      case InputSize.small:
        return const EdgeInsets.symmetric(horizontal: 12, vertical: 8);
      case InputSize.medium:
        return const EdgeInsets.symmetric(horizontal: 16, vertical: 12);
      case InputSize.large:
        return const EdgeInsets.symmetric(horizontal: 20, vertical: 16);
    }
  }

  /// 获取字体大小
  double _getFontSize() {
    switch (widget.inputSize) {
      case InputSize.small:
        return 12;
      case InputSize.medium:
        return 14;
      case InputSize.large:
        return 16;
    }
  }

  /// 获取图标大小
  double _getIconSize() {
    switch (widget.inputSize) {
      case InputSize.small:
        return 18;
      case InputSize.medium:
        return 20;
      case InputSize.large:
        return 22;
    }
  }
}

/// 输入框样式
enum InputStyle {
  outline,
  underline,
  filled,
}

/// 输入框大小
enum InputSize {
  small,
  medium,
  large,
}

/// 搜索输入框组件
class SearchInput extends StatelessWidget {
  final TextEditingController? controller;
  final String? hintText;
  final ValueChanged<String>? onChanged;
  final ValueChanged<String>? onSubmitted;
  final VoidCallback? onClear;
  final bool autofocus;

  const SearchInput({
    super.key,
    this.controller,
    this.hintText,
    this.onChanged,
    this.onSubmitted,
    this.onClear,
    this.autofocus = false,
  });

  @override
  Widget build(BuildContext context) {
    return CommonInput(
      controller: controller,
      hintText: hintText ?? '搜索...',
      prefixIcon: Icons.search,
      suffixIcon: controller?.text.isNotEmpty == true ? Icons.clear : null,
      onSuffixIconTap: () {
        controller?.clear();
        onClear?.call();
      },
      onChanged: onChanged,
      onSubmitted: onSubmitted,
      autofocus: autofocus,
      textInputAction: TextInputAction.search,
      inputStyle: InputStyle.filled,
    );
  }
}
